package com.squareshoot.picCheckin;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreProtocolPNames;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TabHost;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;

public class VenueDetails extends TabActivity{

	private TabHost tabHost;

	private static final int GROUP1 = 10001;
	private static final int ID_CHECKIN = 9990;
	private static final int ID_ADDTIP = 9992;
	private String photoPath=null;
	private Uri photoUri;

	//	private static Runnable displayThumb;
	ArrayList<String> checkins;
	String username,password;
	String venueId,venue,photos;
	double latitude,longitude;
	Bitmap mayorBM;
	DefaultHttpClient httpclient; 
	private GetVenueDetailsTask venueDetailsTask;
	private GetVenuePhotosTask venuePhotosTask;
	private GetMayorPhotoTask mayorPhotoTask;

	private Bundle savedState;
	private Bundle monBundle;

	private JSONObject jVenue;;
	private JSONObject jMayor;
	private JSONObject jUser;
	private JSONObject jPhotos;
	private ImageView mayorPhoto=null;

	MediaScannerConnection m_pScanner;

	public void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.venuedetails);
		if(Common.HIGHDEBUG){
			Log.d(Common.TAG,"VenueDetails : OnCreate");
		}

		httpclient = new DefaultHttpClient();
		Cookie cookie = Common.recupCookie(this);
		if(Common.HIGHDEBUG)
			Log.i(Common.TAG,"cookie : "+cookie);
		httpclient.getCookieStore().addCookie(cookie);
		httpclient.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE,false);

		monBundle = getIntent().getExtras();
		this.username=monBundle.getString("username");
		this.password=monBundle.getString("password");
		this.latitude=monBundle.getDouble("latitude");
		this.longitude=monBundle.getDouble("longitude");
		this.venueId=monBundle.getString("venueId");
		if(monBundle.containsKey("photo")){
			photoUri = (Uri)monBundle.get("photo");
			//			resizeImage();
		}

		Resources res = getResources();
		tabHost = getTabHost();
		TabHost.TabSpec spec;  // Resusable TabSpec for each tab
		spec = tabHost.newTabSpec("venuedetail").setIndicator(getString(R.string.tabVenueDetails),res.getDrawable(R.drawable.placestab)).setContent(R.id.tabVenueDetails);
		tabHost.addTab(spec);
		spec = tabHost.newTabSpec("photos").setIndicator(getString(R.string.photos),res.getDrawable(R.drawable.photostab)).setContent(R.id.tabVenuePhotos);
		tabHost.addTab(spec);
		spec = tabHost.newTabSpec("tips").setIndicator("Tips",res.getDrawable(R.drawable.tabtip)).setContent(R.id.tabVenueTips);
		tabHost.addTab(spec);
		spec = tabHost.newTabSpec("recentcheckins").setIndicator(getString(R.string.tabRecentCheckins),res.getDrawable(R.drawable.recentscheckin)).setContent(R.id.tabRecentCheckin);
		tabHost.addTab(spec);

		if(savedInstanceState==null){
			findViewById(R.id.ScrollView01).setVisibility(View.GONE);
			findViewById(R.id.venueDetailsLoadingLinear).setVisibility(View.VISIBLE);
			findViewById(R.id.venuePhotosLoadingLinear).setVisibility(View.VISIBLE);
			findViewById(R.id.venueTipsLoadingLinear).setVisibility(View.VISIBLE);
			findViewById(R.id.venueCheckinsLoadingLinear).setVisibility(View.VISIBLE);
			venueDetailsTask = new GetVenueDetailsTask();
			venueDetailsTask.setActivity(this);
			venueDetailsTask.execute(venueId);
		}else{
			savedState=savedInstanceState;
			photoPath=savedInstanceState.getString("photoPath");
			photoUri=(Uri)savedInstanceState.get("photoUri");
			venue=savedInstanceState.getString("venue");
			photos=savedInstanceState.getString("photos");

			Object threadRetained=getLastNonConfigurationInstance();
			if(threadRetained!=null){
				if(threadRetained instanceof GetVenueDetailsTask){
					if(Common.HIGHDEBUG)
						Log.d(Common.TAG,"recup venueDetailsTask");
					venueDetailsTask=(GetVenueDetailsTask)threadRetained;
					venueDetailsTask.setActivity(this);
				}
				if(threadRetained instanceof GetVenuePhotosTask){
					if(Common.HIGHDEBUG)
						Log.d(Common.TAG,"recup venuePhotosTask");
					venuePhotosTask=(GetVenuePhotosTask)threadRetained;
					venuePhotosTask.setActivity(this);
				}
			}

			if(venue!=null){
				try{
					jVenue=new JSONObject(venue).getJSONObject("venue");
				}catch(JSONException e){
					e.printStackTrace();
				}
				tabVenueDetail();
				tabVenueTips();
				tabRecentCheckins();
			}
			if(photos!=null){
				try{
					jPhotos=new JSONObject(photos);
				}catch(JSONException e){
					e.printStackTrace();
				}
				tabVenuePhotos();
			}
		}
	}

	public void onResume(){
		super.onResume();
		if(Common.HIGHDEBUG)
			Log.w(Common.TAG,"VenueDetails : onResume");
	}

	@Override
	public void onPause(){
		super.onPause();
		if(Common.HIGHDEBUG)
			Log.w(Common.TAG,"VenueDetails : onPause");
	}

	@Override
	public void onRestoreInstanceState(Bundle savedInstanceState) 
	{
		super.onRestoreInstanceState(savedInstanceState);
		if(Common.HIGHDEBUG)
			Log.w(Common.TAG,"VenueDetails : onRestoreInstantState");
	}

	@Override
	public void onSaveInstanceState(Bundle outState) 
	{
		super.onSaveInstanceState(outState);
		if(Common.HIGHDEBUG)
			Log.w(Common.TAG,"VenueDetails : onSaveInstantState");
		outState.putParcelable("mayorPhoto",mayorBM);
		outState.putString("venue",venue);
		outState.putParcelable("photoUri",photoUri);
		outState.putString("photos",photos);
		if(photoPath!=null)
			outState.putString("photoPath",photoPath);
	}

	public Object onRetainNonConfigurationInstance() {
		if(venueDetailsTask!=null){
			venueDetailsTask.setActivity(null);
			return venueDetailsTask;
		}
		if(venuePhotosTask!=null){
			venuePhotosTask.setActivity(null);
			return venuePhotosTask;
		}
		return null;
	}

	@Override
	protected void onDestroy(){
		super.onDestroy();
		if(Common.HIGHDEBUG)
			Log.w(Common.TAG,"VenueDetails : onDestroy");
		//		camera=null;
		if(mayorPhotoTask!=null && mayorPhotoTask.getStatus() == AsyncTask.Status.RUNNING )
			mayorPhotoTask.cancel(true);
		if(venueDetailsTask!=null && venueDetailsTask.getStatus() == AsyncTask.Status.RUNNING)
			venueDetailsTask.cancel(true);
		if(venuePhotosTask!=null && venuePhotosTask.getStatus() == AsyncTask.Status.RUNNING)
			venuePhotosTask.cancel(true);
		httpclient=null; 
		username=null;
		password=null;
		venueId=null;
		photoPath=null;
		//		System.gc();
	} 

	private void tabVenueTips(){
		if(Common.HIGHDEBUG)
			Log.d(Common.TAG,"tabVenueTips()");

		findViewById(R.id.venueTipsLoadingLinear).setVisibility(View.GONE);

		ArrayList<String> tipsArray = new ArrayList<String>();

		JSONArray jTips = null;
		try{
			jTips = jVenue.getJSONArray("tips");
			if(Common.HIGHDEBUG)
				Log.d(Common.TAG,"jTips : "+jTips);

			String title = jTips.length()+" "+getString(R.string.venueTips);
			((TextView)findViewById(R.id.venueTipsTitle)).setText(title);
			for(int i=0;i<jTips.length();i++){
				JSONObject tip = jTips.getJSONObject(i);
				tipsArray.add(tip.toString());
			}
		}catch(JSONException e){
			if(Common.HIGHDEBUG)
				Log.d(Common.TAG,"Pas de tips dans cet endroit");
			findViewById(R.id.venueTipsNoTips).setVisibility(View.VISIBLE);
		}

		ListView tipsList = (ListView)findViewById(R.id.listVenueTips);
		TipsListAdapter adapter = new TipsListAdapter(this,tipsArray,false);
		tipsList.setAdapter(adapter);
	}

	private void tabVenuePhotos(){
		if(Common.HIGHDEBUG)
			Log.d(Common.TAG,"tabVenuePhotos()");

		final ArrayList<String> photosArray = new ArrayList<String>();

		try{
			JSONObject jMostViewed = jPhotos.getJSONObject("mostviewed");
			photosArray.add(jMostViewed.toString());
		}catch(JSONException e){
			if(Common.HIGHDEBUG)
				Log.d(Common.TAG,"Pas de photo la + vue dans cet endroit");
		}
		try{
			JSONArray photos = jPhotos.getJSONArray("photos");
			for(int i=0;i<photos.length();i++){
				JSONObject photo = photos.getJSONObject(i);
				photosArray.add(photo.toString());
			}
			if(photos.length()==0)
				findViewById(R.id.venueNoPhotos).setVisibility(View.VISIBLE);
		}catch(JSONException e){
			if(Common.HIGHDEBUG)
				Log.d(Common.TAG,"Pas de photos dans cet endroit");
		}

		ListView photosList = (ListView)findViewById(R.id.listVenuePhotos);
		VenuePhotosAdapter adapter = new VenuePhotosAdapter(this,photosArray);
		photosList.setAdapter(adapter);

		photosList.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View view, int position,long id) {
				JSONObject jPicture;
				try {
					jPicture = new JSONObject(photosArray.get(position));
					String photoURL = Common.getBaseImgsUrl()+jPicture.getString("url");
					Intent i = new Intent(VenueDetails.this,FullscreenPicture.class);
					i.putExtra("uri", photoURL);
					startActivity(i);
				} catch (JSONException e) {
				}
			}
		});
	}

	private void tabRecentCheckins(){
		if(Common.HIGHDEBUG)
			Log.d(Common.TAG,"tabRecentCheckins()");
		findViewById(R.id.venueCheckinsLoadingLinear).setVisibility(View.GONE);

		TextView detailsHerenow = (TextView)this.findViewById(R.id.recentHerenow);
		TextView detailsBeenHere = (TextView)findViewById(R.id.recentBeenHere);

		try{
			JSONObject jStats = jVenue.getJSONObject("stats");

			detailsHerenow.setText(getString(R.string.hereNow)+" "+jStats.getString("herenow"));
			String beenhere = jStats.getJSONObject("beenhere").getString("me");
			if(beenhere.compareTo("true")==0)
				detailsBeenHere.setText(getString(R.string.beenHere)+" "+getString(R.string.yes));
			else
				detailsBeenHere.setText(getString(R.string.beenHere)+" "+getString(R.string.no));
		}catch(JSONException e){
			e.printStackTrace();
		}

		if(jVenue.has("checkins")){
			checkins = fillFriendsCheckinsArray(jVenue);
			String title = checkins.size()+" "+getString(R.string.tabRecentCheckins);
			((TextView)findViewById(R.id.recentCheckins)).setText(title);
			ListView checkinsList = (ListView)findViewById(R.id.listrecentCheckins);
			UsersListAdapter adapter = new UsersListAdapter(this,checkins,false);
			checkinsList.setAdapter(adapter);
			setOnClickUser(checkinsList);
		}else{
			findViewById(R.id.venueCheckinsNoCheckins).setVisibility(View.VISIBLE);
		}
	}

	private ArrayList<String> fillFriendsCheckinsArray(JSONObject jDetail){
		ArrayList<String> checkinsArray = new ArrayList<String>();

		try {
			JSONArray jCheckins=jDetail.getJSONArray("checkins");

			for(int i=0;i<jCheckins.length();i++){
				JSONObject user = jCheckins.getJSONObject(i).getJSONObject("user");
				String name = user.getString("firstname");
				if(user.has("lastname"))
					name+=" "+user.getString("lastname");

				JSONObject jUser = new JSONObject();
				jUser.put("name",name);
				jUser.put("photo", user.getString("photo"));
				jUser.put("fsid",user.getString("id"));
				jUser.put("checkin",jCheckins.getJSONObject(i).getString("created"));
				checkinsArray.add(jUser.toString());
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return checkinsArray;
	}

	private void setOnClickUser(final ListView listCheckins){
		listCheckins.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, final View view, final int position,long id) {
				Intent i=new Intent(VenueDetails.this,FriendsAndPhotos.class);
				Bundle bundle = new Bundle();
				bundle.putString("username",username);
				bundle.putString("password",password);
				try {
					final JSONObject user = new JSONObject(checkins.get(position));
					if(Common.HIGHDEBUG)
						Log.d(Common.TAG,"friend : "+user);
					if(user.has("picuserid")){
						bundle.putString("picuserid",user.getString("picuserid"));
					}
					bundle.putString("fsid",user.getString("fsid"));
					if(user.has("email"))
						bundle.putString("email",user.getString("email"));

					ImageView userPhoto = (ImageView)view.findViewById(R.id.userAdapterPhoto);
					BitmapDrawable bmd = (BitmapDrawable)userPhoto.getDrawable();
					bundle.putParcelable("photo",bmd.getBitmap());

					bundle.putString("nomPrenom",user.getString("name"));
				}catch(JSONException e){
					if(Common.HIGHDEBUG)
						Log.d(Common.TAG,"Error JSON : "+e.getMessage());
				}
				bundle.putBoolean("me",false);
				i.putExtras(bundle);
				startActivity(i);
			}
		});
	}

	private void tabVenueDetail(){
		if(Common.HIGHDEBUG)
			Log.d(Common.TAG,"tabVenueDetail()");

		((TableLayout)findViewById(R.id.mayorTable)).setVisibility(View.GONE);
		((ProgressBar)findViewById(R.id.mayorProgressBar)).setVisibility(View.VISIBLE);

		((TextView)findViewById(R.id.seeMapText)).setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				startVenueMap();
			}
		});

		TextView detailsName = (TextView)findViewById(R.id.venueDetailName);
		TextView detailsCategory = (TextView)findViewById(R.id.venueDetailCategorie);
		TextView detailsAddress = (TextView)findViewById(R.id.venueDetailAddress);
		String address = "";

		try {
			detailsName.setText(jVenue.getString("name"));
			if(jVenue.has("primarycategory"))
				detailsCategory.setText(jVenue.getJSONObject("primarycategory").getString("fullpathname"));
			if(jVenue.has("address"))
				address += jVenue.getString("address")+"\n";
			if(jVenue.has("zip"))
				address+=jVenue.getString("zip");
			if(jVenue.has("city"))
				address += " "+jVenue.getString("city");
			if(jVenue.has("state"))
				address += " "+jVenue.getString("state");
			detailsAddress.setText(address);
		} catch (JSONException e) {
			e.printStackTrace();
		}

		String mayorPhotoUrl = null;
		try{
			JSONObject jStats = jVenue.getJSONObject("stats");
			if(jStats.has("mayor")){
				jMayor = jStats.getJSONObject("mayor");
				jUser = jMayor.getJSONObject("user");
				if(Common.HIGHDEBUG)
					Log.d(Common.TAG,"mayor : "+jUser);
				final TextView mayorName = (TextView)findViewById(R.id.venueMayorName);
				mayorPhotoUrl = jUser.getString("photo");

				String name = jUser.getString("firstname");
				if(jUser.has("lastname"))
					name += " "+jUser.getString("lastname");
				mayorName.setText(name);
				TextView mayorTitle = (TextView)findViewById(R.id.mayorTitle);
				mayorTitle.setText(mayorTitle.getText()+" ("+jMayor.getString("count")+" checkins)");
				((LinearLayout)findViewById(R.id.mayorTable)).setOnClickListener(new OnClickListener() {

					public void onClick(View arg0) {
						Intent i=new Intent(VenueDetails.this,FriendsAndPhotos.class);
						Bundle bundle = new Bundle();
						bundle.putString("username",username);
						bundle.putString("password",password);
						try {
							final JSONObject user = jUser;
							if(Common.HIGHDEBUG)
								Log.d(Common.TAG,"friend : "+user);
							if(user.has("picuserid")){
								bundle.putString("picuserid",user.getString("picuserid"));
							}
							bundle.putString("fsid",user.getString("id"));
							if(mayorBM==null){
								if(Common.HIGHDEBUG)
									Log.e(Common.TAG,"mayorBM est null");
							}
							bundle.putParcelable("photo",mayorBM);
							bundle.putString("nomPrenom",mayorName.getText().toString());
						}catch(JSONException e){
							if(Common.HIGHDEBUG)
								Log.d(Common.TAG,"Error JSON : "+e.getMessage());
						}
						bundle.putBoolean("me",false);
						i.putExtras(bundle);
						startActivity(i);
					}
				});
			} else{
				((LinearLayout)findViewById(R.id.MayorLayout)).setVisibility(View.GONE);

			}
		}catch (JSONException e) {
			e.printStackTrace();
		}


		Button upload = (Button)findViewById(R.id.uploadButton);
		upload.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				startCheckin();
			}
		});

		mayorPhoto = (ImageView)findViewById(R.id.venueMayorPhoto);
		if(savedState!=null &&savedState.getParcelable("mayorPhoto")!=null){
			mayorBM = savedState.getParcelable("mayorPhoto");
			mayorPhoto.setImageBitmap(Common.getRoundedCornerBitmap(mayorBM));
			((TableLayout)findViewById(R.id.mayorTable)).setVisibility(View.VISIBLE);
			((ProgressBar)findViewById(R.id.mayorProgressBar)).setVisibility(View.GONE);
		}else{
			mayorPhotoTask = new GetMayorPhotoTask();
			mayorPhotoTask.execute(mayorPhotoUrl);
		}





	}





	private void startCheckin(){
		Intent i = new Intent(VenueDetails.this,CheckinToVenue.class);
		monBundle.putString("photoPath",photoPath);
		if(photoUri!=null)
			monBundle.putParcelable("photoUri",photoUri);
		monBundle.putDouble("latitude", latitude);
		monBundle.putDouble("longitude", longitude);
		if(mayorBM!=null)
			monBundle.putParcelable("mayorPic", mayorBM);
		try {
			monBundle.putString("venue", jVenue.getString("name"));
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		i.putExtras(monBundle);
		startActivity(i);
	}

	private void startVenueMap(){
		double geolat=0,geolong=0;
		try {
			geolat = Double.valueOf(jVenue.getString("geolat"));
			geolong = Double.valueOf(jVenue.getString("geolong"));
		} catch (JSONException e) {
			e.printStackTrace();
		}

		Intent i = new Intent(VenueDetails.this,VenueMap.class);
		Bundle extras = new Bundle();
		extras.putDouble("myLatitude",latitude);
		extras.putDouble("myLongitude",longitude);
		extras.putDouble("geolat",geolat);
		extras.putDouble("geolong",geolong);
		i.putExtras(extras);
		startActivity(i);
	}



	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(GROUP1,ID_CHECKIN,1, getString(R.string.checkinButton)).setIcon(R.drawable.ic_menu_checkin);
		menu.add(GROUP1,ID_ADDTIP,2, getString(R.string.addTip)).setIcon(R.drawable.ic_menu_venue_leave_tip);
		return true;
	}

	/*
	 * Ecouteur du menu
	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
	 */
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case ID_CHECKIN:
			startCheckin();
			return true;
		case ID_ADDTIP:
			Intent i = new Intent(this, AddTip.class);
			Bundle extras = new Bundle();
			extras.putString("username",username);
			extras.putString("password",password);
			extras.putString("venueid",venueId);
			i.putExtras(extras);
			startActivity(i);
		}			
		return false;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu)
	{
		super.onPrepareOptionsMenu(menu);
		if(Common.HIGHDEBUG)
			Log.v(Common.TAG,"onPrepareMenu");

		if(tabHost.getCurrentTabTag().equals("recentcheckins")){
			menu.setGroupVisible(GROUP1, false);
		}
		else{
			menu.setGroupVisible(GROUP1, true);
		}
		return true;
	}

	private void onThreadVenuesCompleted(Bundle data){
		findViewById(R.id.venueDetailsLoadingLinear).setVisibility(View.GONE);
		findViewById(R.id.ScrollView01).setVisibility(View.VISIBLE);
		if(data.containsKey("venue")){
			venue = data.getString("venue");
			if(Common.HIGHDEBUG)
				Log.d(Common.TAG,"venue : "+venue);
			try {
				jVenue = (new JSONObject((venue))).getJSONObject("venue");
			} catch (JSONException e) {
				Log.d(Common.TAG,"Could not parse json response");
			}
			venuePhotosTask = new GetVenuePhotosTask();
			venuePhotosTask.setActivity(this);
			venuePhotosTask.execute(venueId);
			tabVenueDetail();
			tabVenueTips();
			tabRecentCheckins();
		}else{
			Toast erreurToast = Toast.makeText(VenueDetails.this,data.getString("eMessage"),Toast.LENGTH_SHORT);
			erreurToast.setGravity(Gravity.CENTER, 0, 0);
			erreurToast.show();
		}
	}

	private void onThreadPhotosCompleted(Bundle data){
		findViewById(R.id.venuePhotosLoadingLinear).setVisibility(View.GONE);
		//		findViewById(R.id.ScrollView01).setVisibility(View.VISIBLE);
		if(data.containsKey("photos")){
			photos = data.getString("photos");
			if(Common.HIGHDEBUG)
				Log.d(Common.TAG,"photos : "+photos);
			try {
				jPhotos = new JSONObject(photos);
			} catch (JSONException e) {
				Log.d(Common.TAG,"Could not parse json response");
			} catch (NullPointerException e) {
				Log.d(Common.TAG,"Could not parse json response");
			}
			if(Common.HIGHDEBUG)
				Log.d(Common.TAG,"jPhotos: "+jPhotos);
			tabVenuePhotos();
		}else{
			Toast erreurToast = Toast.makeText(VenueDetails.this,data.getString("eMessage"),Toast.LENGTH_SHORT);
			erreurToast.setGravity(Gravity.CENTER, 0, 0);
			erreurToast.show();
		}
	}



	boolean mExternalStorageAvailable = false;
	boolean mExternalStorageWriteable = false;
	public boolean fromGallerie =false;

	void updateExternalStorageState() {
		String state = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(state)) {
			mExternalStorageAvailable = mExternalStorageWriteable = true;
		} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
			mExternalStorageAvailable = true;
			mExternalStorageWriteable = false;
		} else {
			mExternalStorageAvailable = mExternalStorageWriteable = false;
		}
	}


	private class GetVenueDetailsTask extends AsyncTask<String,String,Message>{
		private VenueDetails activity;
		private boolean completed=false;
		private Message msg;

		protected Message doInBackground(String... parameters) {
			msg=Message.obtain();
			Bundle data = new Bundle();

			String urlVenueDetails = "http://api.foursquare.com/v1/venue.json?vid="+parameters[0];
			String detailsVenue = null;
			try {
				detailsVenue = Common.getUrlDataAuth(urlVenueDetails,username,password);
				data.putString("venue",detailsVenue);
			} catch (IOException e) {
				data.putString("eMessage",e.getMessage());
			}
			msg.setData(data);
			return msg;
		}

		protected void onPostExecute(Message msg) {
			completed=true;
			if(activity!=null)
				endTask();
		}

		private void setActivity(VenueDetails activity) {
			this.activity = activity;
			if ( completed ) {
				endTask();
			}
		}

		private void endTask(){
			activity.venueDetailsTask=null;
			activity.onThreadVenuesCompleted(msg.getData());
		}
	}

	private class GetVenuePhotosTask extends AsyncTask<String,String,Message>{
		private VenueDetails activity;
		private boolean completed=false;
		private Message msg;

		protected Message doInBackground(String... parameters) {
			msg=Message.obtain();
			Bundle data = new Bundle();

			String urlVenuePhotos = Common.getBaseUrl()+"/venuephotos";
			String venuePhotos = null;
			try {
				Log.d(Common.TAG,"vid="+parameters[0]);
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("user", username));
				params.add(new BasicNameValuePair("password", password));
				params.add(new BasicNameValuePair("vid",parameters[0]));
				venuePhotos = Common.postUrlData(httpclient, urlVenuePhotos, params);
				data.putString("photos",venuePhotos);
			} catch (IOException e) {
				data.putString("eMessage",e.getMessage());
			}
			msg.setData(data);
			return msg;
		}

		protected void onPostExecute(Message msg) {
			completed=true;
			if(activity!=null)
				endTask();
		}

		private void setActivity(VenueDetails activity) {
			this.activity = activity;
			if ( completed ) {
				endTask();
			}
		}

		private void endTask(){
			activity.venuePhotosTask=null;
			activity.onThreadPhotosCompleted(msg.getData());
		}
	}

	private class GetMayorPhotoTask extends AsyncTask<String,String,Bitmap>{
		protected Bitmap doInBackground(String... parameters) {
			try {
				mayorBM = Common.downloadImage(parameters[0]);
			} catch (IOException e) {
				if(Common.HIGHDEBUG)
					Log.d(Common.TAG,"get mayor photo : "+e.getMessage());
				return null;
			}
			return mayorBM;
		}

		protected void onPostExecute(Bitmap bm) {
			mayorPhotoTask=null;
			if(mayorBM!=null){
				mayorPhoto.setImageBitmap(Common.getRoundedCornerBitmap(mayorBM));
				((TableLayout)findViewById(R.id.mayorTable)).setVisibility(View.VISIBLE);
				((ProgressBar)findViewById(R.id.mayorProgressBar)).setVisibility(View.GONE);
			}
		}
	}
}
